<template>
  <div class="new-books-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="keyword"
        placeholder="搜索书名、作者或ISBN..."
        size="large"
        clearable
        @input="handleSearch"
        class="search-input"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button
        v-if="authStore.isAdmin"
        type="primary"
        size="large"
        @click="handleAddBook"
        :icon="Plus"
      >
        新增推荐图书
      </el-button>
    </div>

    <!-- 图书卡片网格 -->
    <div v-loading="loading" class="books-grid">
      <div
        v-for="book in books"
        :key="book.id"
        class="book-card"
        :class="{ 'out-of-stock': book.stock <= 0 }"
        @click="handleViewDetail(book)"
      >
        <div class="book-cover">
          <div class="cover-placeholder">
            <el-icon size="60"><Document /></el-icon>
          </div>
          <div v-if="book.stock <= 0" class="stock-badge out">缺货</div>
          <div v-else-if="book.stock <= 3" class="stock-badge low">仅剩{{ book.stock }}本</div>
        </div>
        
        <div class="book-info">
          <h3 class="book-title" :title="book.title">{{ book.title }}</h3>
          <p class="book-author">
            <el-icon><User /></el-icon>
            {{ book.author }}
          </p>
          <div class="book-meta">
            <el-tag v-if="book.category" size="small" type="info">{{ book.category }}</el-tag>
            <span class="stock-info">
              <el-icon><Box /></el-icon>
              库存: {{ book.stock }}
            </span>
          </div>
          <p v-if="book.description" class="book-description" :title="book.description">
            {{ book.description.length > 60 ? book.description.substring(0, 60) + '...' : book.description }}
          </p>
        </div>

        <div class="book-actions">
          <el-button
            v-if="!authStore.isAdmin"
            type="primary"
            :disabled="book.stock <= 0"
            @click.stop="handleBorrow(book)"
            class="action-btn"
          >
            <el-icon><ShoppingCart /></el-icon>
            借阅
          </el-button>
          <el-button
            v-if="!authStore.isAdmin"
            type="danger"
            :icon="getFavoriteIcon(book.id)"
            @click.stop="handleToggleFavorite(book)"
            class="action-btn"
            text
          >
            {{ getFavoriteText(book.id) }}
          </el-button>
          <el-button
            v-if="!authStore.isAdmin && book.stock <= 0"
            type="warning"
            @click.stop="handleReserve(book)"
            class="action-btn"
            text
          >
            <el-icon><Clock /></el-icon>
            预约
          </el-button>
          <template v-else>
            <el-button
              type="warning"
              @click.stop="handleEdit(book)"
              class="action-btn"
            >
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button
              type="info"
              @click.stop="handleCancelRecommend(book)"
              class="action-btn"
            >
              <el-icon><Remove /></el-icon>
              取消推荐
            </el-button>
          </template>
        </div>
      </div>

      <el-empty v-if="!loading && books.length === 0" description="暂无推荐图书" />
    </div>

    <!-- 新增/编辑图书对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      @close="resetForm"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="书名" prop="title">
          <el-input v-model="form.title" placeholder="请输入书名" />
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="form.author" placeholder="请输入作者" />
        </el-form-item>
        <el-form-item label="ISBN">
          <el-input v-model="form.isbn" placeholder="请输入ISBN" />
        </el-form-item>
        <el-form-item label="分类">
          <el-input v-model="form.category" placeholder="请输入分类" />
        </el-form-item>
        <el-form-item label="库存">
          <el-input-number v-model="form.stock" :min="0" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Document, User, Box, ShoppingCart, Edit, Remove, Star, StarFilled, Clock } from '@element-plus/icons-vue'
import { useAuthStore } from '../stores/auth'
import { bookAPI, favoriteAPI, reservationAPI, borrowAPI } from '../services/api'

const router = useRouter()
const authStore = useAuthStore()
const books = ref([])
const favorites = ref(new Set())
const loading = ref(false)
const keyword = ref('')
const dialogVisible = ref(false)
const dialogTitle = ref('新增推荐图书')
const formRef = ref(null)
const editingId = ref(null)

const form = reactive({
  title: '',
  author: '',
  isbn: '',
  category: '',
  stock: 0,
  description: ''
})

const rules = {
  title: [{ required: true, message: '请输入书名', trigger: 'blur' }],
  author: [{ required: true, message: '请输入作者', trigger: 'blur' }]
}

const fetchBooks = async () => {
  loading.value = true
  try {
    const response = await bookAPI.searchBooks({
      is_recommended: 'true',
      keyword: keyword.value || undefined
    })
    books.value = response.books || []
    
    // 检查收藏状态
    if (!authStore.isAdmin && books.value.length > 0) {
      await checkFavorites()
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '获取图书列表失败')
  } finally {
    loading.value = false
  }
}

const checkFavorites = async () => {
  try {
    const promises = books.value.map(book => 
      favoriteAPI.checkFavorite(book.id).catch(() => ({ isFavorite: false }))
    )
    const results = await Promise.all(promises)
    results.forEach((result, index) => {
      if (result.isFavorite) {
        favorites.value.add(books.value[index].id)
      }
    })
  } catch (error) {
    // 静默失败
  }
}

const handleSearch = () => {
  fetchBooks()
}

const handleViewDetail = (book) => {
  router.push({ name: 'BookDetail', params: { id: book.id } })
}

const handleBorrow = async (book) => {
  try {
    await ElMessageBox.confirm(`确定要借阅《${book.title}》吗？`, '确认借阅', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })
    
    await borrowAPI.borrowBook(book.id)
    ElMessage.success('借阅成功')
    await fetchBooks()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '借阅失败')
    }
  }
}

const handleToggleFavorite = async (book) => {
  try {
    const isFavorite = favorites.value.has(book.id)
    if (isFavorite) {
      await favoriteAPI.removeFavorite(book.id)
      favorites.value.delete(book.id)
      ElMessage.success('取消收藏成功')
    } else {
      await favoriteAPI.addFavorite(book.id)
      favorites.value.add(book.id)
      ElMessage.success('收藏成功')
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '操作失败')
  }
}

const handleReserve = async (book) => {
  try {
    await ElMessageBox.confirm(`确定要预约《${book.title}》吗？`, '确认预约', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })
    
    await reservationAPI.reserveBook(book.id)
    ElMessage.success('预约成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '预约失败')
    }
  }
}

const getFavoriteIcon = (bookId) => {
  return favorites.value.has(bookId) ? StarFilled : Star
}

const getFavoriteText = (bookId) => {
  return favorites.value.has(bookId) ? '已收藏' : '收藏'
}

const handleAddBook = () => {
  dialogTitle.value = '新增推荐图书'
  editingId.value = null
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (book) => {
  dialogTitle.value = '编辑推荐图书'
  editingId.value = book.id
  Object.assign(form, {
    title: book.title,
    author: book.author,
    isbn: book.isbn || '',
    category: book.category || '',
    stock: book.stock,
    description: book.description || ''
  })
  dialogVisible.value = true
}

const handleCancelRecommend = async (book) => {
  try {
    await ElMessageBox.confirm(`确定要取消《${book.title}》的推荐吗？`, '确认取消推荐', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await bookAPI.updateBook(book.id, {
      ...book,
      isRecommended: false
    })
    ElMessage.success('已取消推荐')
    await fetchBooks()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '操作失败')
    }
  }
}

const resetForm = () => {
  Object.assign(form, {
    title: '',
    author: '',
    isbn: '',
    category: '',
    stock: 0,
    description: ''
  })
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const bookData = {
          ...form,
          isRecommended: true  // 新增推荐图书时自动设置为推荐
        }
        
        if (editingId.value) {
          await bookAPI.updateBook(editingId.value, {
            ...bookData,
            isRecommended: true  // 编辑时保持推荐状态
          })
          ElMessage.success('更新成功')
        } else {
          await bookAPI.createBook(bookData)
          ElMessage.success('添加成功')
        }
        dialogVisible.value = false
        await fetchBooks()
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '操作失败')
      }
    }
  })
}

onMounted(() => {
  fetchBooks()
})
</script>

<style scoped>
.new-books-container {
  height: 100%;
  padding: 24px;
  background: linear-gradient(to bottom, #f5f7fa 0%, #ffffff 100%);
}

.search-bar {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.search-input {
  flex: 1;
  max-width: 500px;
}

.books-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 24px;
  min-height: 400px;
}

.book-card {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  height: 100%;
  cursor: pointer;
}

.book-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.book-card.out-of-stock {
  opacity: 0.7;
}

.book-cover {
  position: relative;
  height: 200px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}

.cover-placeholder {
  color: rgba(255, 255, 255, 0.9);
}

.stock-badge {
  position: absolute;
  top: 12px;
  right: 12px;
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: bold;
  color: white;
}

.stock-badge.out {
  background: rgba(245, 108, 108, 0.9);
}

.stock-badge.low {
  background: rgba(255, 193, 7, 0.9);
}

.book-info {
  padding: 20px;
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.book-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-height: 1.4;
  min-height: 50px;
}

.book-author {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #606266;
  font-size: 14px;
  margin: 0;
}

.book-meta {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  flex-wrap: wrap;
}

.stock-info {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #909399;
  font-size: 13px;
}

.book-description {
  color: #909399;
  font-size: 13px;
  line-height: 1.6;
  margin: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.book-actions {
  padding: 16px 20px;
  border-top: 1px solid #ebeef5;
  display: flex;
  gap: 8px;
}

.action-btn {
  flex: 1;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .books-grid {
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 16px;
  }
  
  .search-bar {
    flex-direction: column;
  }
  
  .search-input {
    max-width: 100%;
  }
}
</style>

